package com.sure0000.thread;

import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.Future;
import java.util.concurrent.RecursiveTask;

public class ForkJoin {

    public static class CountTask extends RecursiveTask<Integer> {
        private static final int THRESHOLD = 100;
        private int start;
        private int end;

        public CountTask(int start, int end) {
            this.start = start;
            this.end = end;
        }

        @Override
        protected Integer compute() {
            Integer sum = 0;
            // 判断是否需要拆分
            if(end - start > THRESHOLD) {
                int middle = (start + end)/2;
                // 拆分为左右两个任务
                CountTask leftTask = new CountTask(start, middle);
                CountTask rightTask = new CountTask(middle + 1, end);
                leftTask.fork();
                rightTask.fork();

                int leftResult = leftTask.join();
                int rightResult = rightTask.join();
                sum = leftResult + rightResult;
            }else{
                for(int i = start; i <= end; i++) {
                    sum = sum + i;
                }
            }
            return sum;
        }
    }

    public static void main(String[] args) throws Exception {
        long sTime = System.currentTimeMillis(); 
        int start = 1;
        int end = 10000;

        int systemCores = Runtime.getRuntime().availableProcessors();
        int parallelism = systemCores;
        ForkJoinPool forkJoinPool = new ForkJoinPool(parallelism);
        CountTask countTask = new CountTask(start, end);
        Future<Integer> future = forkJoinPool.submit(countTask);
        System.out.println(future.get());

        // int sum = 0;
        // for(int i = start; i <= end; i++) {
        //     sum = sum + i;
        // }
        // System.out.println(sum);

        
        long eTime = System.currentTimeMillis();
        System.out.println(eTime - sTime);
        
    }
}